import java.awt.*;
import java.util.List;
import javax.swing.*;

/**
 * 计时器主窗口类，实现任务计时器的图形界面
 */
public class TimerFrame extends JFrame {
    // 数据库访问对象
    private TaskDAO dao = new TaskDAO();
    
    // 任务列表相关组件
    private DefaultListModel<Task> listModel = new DefaultListModel<>();
    private JList<Task> taskList = new JList<>(listModel);
    
    // 计时器显示组件
    private JLabel timerLabel = new JLabel("00:00:00", SwingConstants.CENTER);
    
    // 控制按钮
    private JButton btnStart = new JButton("开始");
    private JButton btnPause = new JButton("暂停");
    private JButton btnReset = new JButton("重置");
    private JButton btnFinish = new JButton("完成任务");
    private JButton btnAdd = new JButton("添加任务");
    private JButton btnDelete = new JButton("删除任务");
    
    // 面板
    private JPanel leftPanel;
    private JPanel rightPanel;
    
    // 计时器相关变量
    private Timer swingTimer;        // Swing定时器
    private long startTime;          // 开始时间
    private long elapsedTime;        // 已过时间
    private boolean running = false; // 是否正在运行
    private Task currentTask = null; // 当前选中的任务

    /**
     * 构造函数，初始化界面
     */
    public TimerFrame() {
        setTitle("任务计时器");
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 初始化左侧任务列表面板
        initLeftPanel();
        
        // 初始化右侧计时器面板
        initRightPanel();
        
        // 设置主布局
        setLayout(new GridLayout(1, 2));
        add(leftPanel);
        add(rightPanel);

        // 初始化事件监听
        initEventListeners();
        
        // 初始化计时器
        initTimer();
        
        // 刷新任务列表
        refreshTaskList();
    }

    /**
     * 初始化左侧任务列表面板
     */
    private void initLeftPanel() {
        leftPanel = new JPanel(new BorderLayout());
        leftPanel.add(new JScrollPane(taskList), BorderLayout.CENTER);
        
        JPanel leftBtnPanel = new JPanel();
        leftBtnPanel.add(btnAdd);
        leftBtnPanel.add(btnDelete);
        leftPanel.add(leftBtnPanel, BorderLayout.SOUTH);
    }

    /**
     * 初始化右侧计时器面板
     */
    private void initRightPanel() {
        rightPanel = new JPanel(new BorderLayout());
        timerLabel.setFont(new Font("Arial", Font.BOLD, 48));
        timerLabel.setForeground(Color.RED);
        rightPanel.add(timerLabel, BorderLayout.CENTER);

        JPanel timerBtnPanel = new JPanel();
        timerBtnPanel.add(btnStart);
        timerBtnPanel.add(btnPause);
        timerBtnPanel.add(btnReset);
        timerBtnPanel.add(btnFinish);
        rightPanel.add(timerBtnPanel, BorderLayout.SOUTH);
    }

    /**
     * 初始化事件监听器
     */
    private void initEventListeners() {
        // 添加任务按钮事件
        btnAdd.addActionListener(e -> {
            String name = JOptionPane.showInputDialog(this, "请输入任务名称：");
            if (name != null && !name.trim().isEmpty()) {
                dao.addTask(name.trim());
                refreshTaskList();
            }
        });

        // 删除任务按钮事件
        btnDelete.addActionListener(e -> {
            Task t = taskList.getSelectedValue();
            if (t != null) {
                dao.deleteTask(t.getId());
                refreshTaskList();
            }
        });

        // 计时器控制按钮事件
        btnStart.addActionListener(e -> startTimer());
        btnPause.addActionListener(e -> pauseTimer());
        btnReset.addActionListener(e -> resetTimer());
        btnFinish.addActionListener(e -> finishTask());

        // 任务列表选择事件
        taskList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                currentTask = taskList.getSelectedValue();
                resetTimer();
            }
        });
    }

    /**
     * 初始化计时器
     */
    private void initTimer() {
        swingTimer = new Timer(1000, e -> {
            elapsedTime = System.currentTimeMillis() - startTime;
            updateTimerLabel();
        });
    }

    /**
     * 刷新任务列表
     */
    private void refreshTaskList() {
        listModel.clear();
        List<Task> tasks = dao.getAllTasks();
        for (Task t : tasks) listModel.addElement(t);
    }

    /**
     * 开始计时
     */
    private void startTimer() {
        if (currentTask == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个任务！");
            return;
        }
        if (!running) {
            startTime = System.currentTimeMillis() - elapsedTime;
            swingTimer.start();
            running = true;
        }
    }

    /**
     * 暂停计时
     */
    private void pauseTimer() {
        if (running) {
            swingTimer.stop();
            elapsedTime = System.currentTimeMillis() - startTime;
            running = false;
        }
    }

    /**
     * 重置计时器
     */
    private void resetTimer() {
        swingTimer.stop();
        elapsedTime = 0;
        updateTimerLabel();
        running = false;
    }

    /**
     * 更新计时器显示
     */
    private void updateTimerLabel() {
        long seconds = elapsedTime / 1000;
        timerLabel.setText(String.format("%02d:%02d:%02d", seconds/3600, (seconds%3600)/60, seconds%60));
    }

    /**
     * 完成任务
     */
    private void finishTask() {
        if (currentTask == null) {
            JOptionPane.showMessageDialog(this, "请先选择一个任务！");
            return;
        }
        pauseTimer();
        int duration = (int)(elapsedTime / 1000);
        java.util.Date now = new java.util.Date();
        dao.finishTask(currentTask.getId(), new java.util.Date(startTime), now, duration);
        JOptionPane.showMessageDialog(this, "任务完成！用时：" + duration + "秒");
        refreshTaskList();
        resetTimer();
    }
}